<template>
  <div class="mengli-set">
    <!-- <Title v-if="!hideTitle" title="萌力星球" class="mb20"/> -->
    <div :style="hideTitle?{paddingLeft: 0}:{}" class="mengli-tab-main">
      <div class="main-title">IP系列管理</div>
      <template v-if="!showMobilePage">
        <el-button v-if="isAdmin || hasRouteAuth('system:ipSeries:read')" class="btn" type="primary" plain size="small" @click="toOpenTable">查看IP系列列表</el-button>
        <el-button v-if="isAdmin || hasRouteAuth('system:ipSeries:create')" class="btn" type="primary" plain size="small" @click="addItem">添加IP系列</el-button>
      </template>
      <template v-else>
        <div v-if="isAdmin || hasRouteAuth('system:ipSeries:read')" class="mobile-link-btn" @click="toOpenTable">查看IP系列列表</div>
        <div v-if="isAdmin || hasRouteAuth('system:ipSeries:create')" class="mobile-link-btn mobile-btn-left" @click="addItem">添加IP系列</div>
      </template>
    </div>
    <!-- 新增编辑IP系列 开始 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :append-to-body="false"
      class="order-setting-dialog small-common-dialog-size"
      width="450px">
      <div class="main">
        <Title :title="!isEdit?'添加IP系列':'编辑IP系列'" font-size="16px" style="margin-bottom:20px;"/>
        <el-form
          ref="configForm"
          :rules="rules"
          :model="queryData"
          label-position="right"
          label-width="100px"
          class="setting-form">
          <el-form-item label="IP系列名称" prop="name" class="mb30">
            <el-input
              v-model="queryData.name"
              style="font-size: 13px;width:240px;"
              type="text"
              size="small"
              maxlength="20"
              placeholder="最多20个字符"/>
          </el-form-item>
        </el-form>
        <div class="btn-container">
          <el-button :loading="btnLoading" type="primary" size="small" @click="handleOk">确定</el-button>
          <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose()">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 新增编辑IP系列 结束 -->
    <!-- IP系列列表 开始 -->
    <el-dialog
      :visible.sync="tableShow"
      :before-close="costTableClose"
      :append-to-body="false"
      class="large-common-dialog-size create-settle-dialog cost-config-dialog"
    >
      <div class="flex" style="margin-bottom:10px;">
        <Title title="IP系列管理" font-size="16px"/>
        <PlainCreateBtn v-if="hasRouteAuth('system:ipSeries:create')" @click="addItem">添加</PlainCreateBtn>
      </div>
      <el-table
        v-loading="listloading"
        :data="listData.items"
        :max-height="tableHeight"
        class="fb-table"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row>
        <el-table-column align="left" label="IP系列">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.name && scope.row.name.length > 20" class="item" placement="top" effect="dark">
              <div slot="content">{{ scope.row.name }}</div>
              <div class="ellipsisOne">{{ scope.row.name }}</div>
            </el-tooltip>
            <div v-else class="ellipsisOne">{{ scope.row.name || '--' }}</div>
          </template>
        </el-table-column>
        <el-table-column v-if="isAdmin || hasRouteAuth('system:ipSeries:edit') || hasRouteAuth('system:ipSeries:delete')" align="left" label="操作" width="100">
          <template slot-scope="scope">
            <el-button v-if="isAdmin || hasRouteAuth('system:ipSeries:edit')" type="text" @click="editItem(scope.row)"><span style="font-size:14px;">编辑</span></el-button>
            <el-button v-if="isAdmin || hasRouteAuth('system:ipSeries:delete')" type="text" @click="deleteItem(scope.row.id)"><span style="font-size:14px;">删除</span></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end">
        <el-pagination
          :current-page="page"
          :page-size="perPage"
          :total="listData.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="showMobilePage?'total, prev, next, jumper':'total, prev, pager, next, sizes, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
    </el-dialog>
    <!-- IP系列列表 结束 -->
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage from '@/utils/message';
// 组件
import Title from '@/components/Title';
// api
import { getMengliIpSeries, createMengliIpSeries, editMengliIpSeries, mengliIpSeriesDel } from '@/api/mengli';
// image
import setting from '@/assets/setting.png';
export default {
  name: 'MengliIpConfig',
  components: {
    Title
  },
  props: {
    hideTitle: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateName = (msg) => {
      return (rule, value, callback) => {
        const name = this.queryData.name;
        if (!name || name === '') { callback(new Error(msg)); } else { callback(); }
      };
    };
    return {
      setting,
      rules: {
        name: [{ required: true, trigger: 'blur', validator: validateName('请输入IP系列名称') }]
      },
      queryData: {
        name: ''
      },
      page: 1,
      perPage: 20,
      listloading: false,
      listData: {
        items: []
      },
      isEdit: false,
      dialogVisible: false,
      tableShow: false,
      btnLoading: false,
      tableHeight: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage,
      'userInfo': state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    }
  },
  created() {
    this.getData();
  },
  methods: {
    hasRouteAuth,
    getData(reset) {
      if (reset) this.page = 1;
      const { page, perPage } = this;
      const params = {
        page,
        perPage
      };
      this.listloading = true;
      getMengliIpSeries(params).then(res => {
        this.listloading = false;
        if (res.code === 200) {
          this.listData = res.data;
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.listloading = false;
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.queryData = {
        name: ''
      };
    },
    editItem(item) {
      if (this.$refs.configForm) this.$refs.configForm.clearValidate(); // 清空校验
      this.queryData = JSON.parse(JSON.stringify(item));
      this.isEdit = true;
      this.dialogVisible = true;
    },
    addItem() {
      this.isEdit = false;
      this.dialogVisible = true;
      if (this.$refs.configForm) this.$refs.configForm.clearValidate();// 清空校验
    },
    handleOk() {
      const paramsObj = JSON.parse(JSON.stringify(this.queryData));
      this.$refs.configForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.edit(paramsObj);
          } else {
            this.add(paramsObj);
          }
        } else {
          return false;
        }
      });
    },
    edit(params) {
      this.btnLoading = true;
      params.ipSeriesName = params.name;
      params.ipSeriesId = params.id;
      editMengliIpSeries(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.handleClose();
          this.getData();
          ElMessage.success('保存成功');
        } else {
          ElMessage.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    add(params) {
      this.btnLoading = true;
      params.ipSeriesName = params.name;
      createMengliIpSeries(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.handleClose();
          this.getData(true);
          ElMessage.success('请求成功');
        } else {
          ElMessage.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    // 表格展示
    toOpenTable() {
      const clientHeight = window.innerHeight;
      this.tableHeight = (clientHeight * 3) / 5;
      this.tableShow = true;
    },
    costTableClose() {
      this.tableShow = false;
    },
    deleteItem(id) {
      this.$confirm('是否确定删除该IP系列？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        mengliIpSeriesDel({ ipSeriesId: id }).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getData();
          } else {
            this.$message.error(res.message);
          }
        }).catch(err => {
          // const { message = '出错啦，请再次尝试。' } = err;
          // this.$message.error(message);
          console.error(err);
        });
      }).catch(() => {});
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getData();
    }
  }
};
</script>
<style lang="scss" scoped>
.flex {
  display: flex;
  align-items: center;
}
</style>
